package sb.simple.schedule.way_dynamic;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.config.TriggerTask;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Repository;
import org.sqlite.util.StringUtils;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * 动态读取数据中定时规则
 */
@Configuration
@EnableScheduling
public class DynamicScheduleTask implements SchedulingConfigurer {

    /*@Repository
    @Mapper
    public interface CronMapper {
        @Select("select cron from schedule limit 1")
        String getCron();
    }

    @Autowired
    CronMapper cronMapper;*/

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        //任务内容
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                //System.out.println("执行动态任务:" + LocalDateTime.now());
            }
        };
        //配置执行周期
        Trigger trigger = new Trigger() {
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {
                //System.out.println("读取库中动态配置的corn:");
                /*Date date = null;
                String cron = cronMapper.getCron();
                System.out.println("读取数据库动态cron:" + cron);
                if (null != cron && !cron.isEmpty()) {
                    date = new CronTrigger(cron).nextExecutionTime(triggerContext);
                }
                return date;*/
                return new CronTrigger("0/5 * * * * ?").nextExecutionTime(triggerContext);
            }
        };
        scheduledTaskRegistrar.addTriggerTask(new TriggerTask(runnable, trigger));
    }
}
